package com.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yz.common.CustomException;
import com.yz.common.R;
import com.yz.entity.Category;
import com.yz.entity.Dish;
import com.yz.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 获取 菜品分类和套餐分类 的分页数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> getPage(Integer page, Integer pageSize){
        //分页构造器
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //条件构造器 升序排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        wrapper.orderByDesc(Category::getUpdateTime);
        categoryService.page(categoryPage,wrapper);
        return R.success(categoryPage);
    }

    /**
     * 添加菜品分类或者套餐分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
//        String name = category.getName();
//        //1、判断菜品分类是否符合标准
//        if(category.getType() == 1){
//            name = StringUtils.removeEnd(name,"套餐");
//        }else{
//            if(!StringUtils.contains(name,"套餐"))
//                name += "套餐";
//        }

        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 删除菜品分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        log.info("删除分类，id:{}",ids);

        categoryService.removeById(ids);
        return R.success("已删除");
    }

    /**
     * 修改菜品分类数据
     * @param category
     * @return
     */
    @PutMapping
    public R<String> edit(@RequestBody Category category){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName,category.getName());
        int count = categoryService.count(wrapper);
        if(count > 0){
            throw new CustomException("已存在该菜名");
        }
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

    /**
     * 获取菜品类型 列表数据
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(@RequestParam(required = false) Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null,Category::getType,type);
        wrapper.orderByAsc(Category::getSort);
        wrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list =  categoryService.list(wrapper);
        return R.success(list);
    }
}
